import {createSlice} from '@reduxjs/toolkit'
import axios from "axios"

const billStore = createSlice({

    name: "bill",
    initialState: {
        billList: [],
    },
    reducers: {
        // 添加异步请求回来的数据
        setBillList(state, action) {
            state.billList = action.payload
        },
        // 添加新增账单数据
        addBillList(state, action) {
            state.billList.push(action.payload)
        },
    }
})

// 解构actionCreater函数
const {setBillList,addBillList} = billStore.actions

// 编写异步
const getBillList = () => {
    return async dispatch => {
        // 编写异步请求
        const res = await axios.get("http://localhost:8888/ka")
        // 触发同步reducer
        dispatch(setBillList(res.data))
    }
}

const addList = (data) => {
    return async (dispatch) => {
        // 编写异步请求
        const res = await axios.post("http://localhost:8888/ka",data)
        // 触发同步reducer
        dispatch(addBillList(res.data))
    }
}
// 按需导出
export {getBillList, addList}

//导出reducer

const reducer = billStore.reducer

export default reducer